<template>
  <div class="search">
    <Row>
      <Col>
        <Card>
          <Row class="operation">
            <Form inline :label-width="170" ref="form" :model="form" label-position="right">
              <Button @click="getDataList" icon="md-refresh">刷新</Button>
              <Button @click="add" type="primary" icon="md-add">添加</Button>

              <Form-item label="广告类型" prop="advertisingType">
                <Select v-model="searchForm.advertisingType" clearable style="width:200%">
                  <Option value="OPEN_HOME">开屏</Option>
                  <Option value="BANNER">轮播</Option>
                </Select>
              </Form-item>
              <FormItem label="广告跳转类型" prop="advertisingJumpType">
                <Select v-model="searchForm.advertisingJumpType" clearable style="width:200%">
                  <Option value="H5_WEB">外部链接</Option>
                  <Option value="STORE_HOME">商家首页</Option>
                  <Option value="GOOD_PAGE">商品详情页</Option>
                  <Option value="GOOD_PACKAGE_PAGE">作品详情页</Option>
                </Select>
              </FormItem>
              <Button @click="getDataList" type="primary" icon="ios-search" style="margin-left:90px;">搜索</Button>
            </Form>
          </Row>
          <Row>
            <Alert show-icon>
              已选择 <span class="select-count">{{selectCount}}</span> 项
              <a class="select-clear" @click="clearSelectAll">清空</a>
            </Alert> 
          </Row>
          <Row>
            <Table :loading="loading" border :columns="columns" :data="data" ref="table" sortable="custom" @on-sort-change="changeSort"></Table>
          </Row>
          <Row type="flex" justify="end" class="page">
            <Page :current="searchForm.pageNumber" :total="total" :page-size="searchForm.pageSize" @on-change="changePage" @on-page-size-change="changePageSize" :page-size-opts="[10,20,50]" size="small" show-total show-elevator show-sizer></Page>
          </Row>
        </Card>
      </Col>
    </Row>
    <Modal :title="modalTitle" v-model="modalVisible" :mask-closable='false' :width="700">
      <Form ref="form" :model="form" :label-width="100" :rules="formValidate" >
        <Form-item label="广告类型" prop="advertisingType">
          <Select v-model="form.advertisingType" style="width:100%" @on-change="changeType">
            <Option value="OPEN_HOME">开屏</Option>
            <Option value="BANNER">轮播</Option>
          </Select>
        </Form-item>
        <Form-item label="广告跳转类型" prop="advertisingJumpType">
          <Select v-model="form.advertisingJumpType" style="width:100%" @on-change="selectAdvertType">
            <Option value="H5_WEB">外部链接</Option>
            <Option value="STORE_HOME">商家首页</Option>
            <Option value="GOOD_PAGE">商品详情页</Option>
            <Option value="GOOD_PACKAGE_PAGE">作品详情页</Option>
          </Select>
        </Form-item>
        <FormItem label="文件" prop="pic" >
          <upload-video-input v-model="form.pic"></upload-video-input>
        </FormItem>
        <FormItem label="跳转链接" prop="url" v-if="advertType === 'H5_WEB'">
          <!-- <Input v-model="form.url" style="width:100%" placeholder="请输入跳转链接"/> -->
          <i-input v-model="form.url" style="width:100%" placeholder="请输入跳转链接">
            <span slot="prepend">https://</span>
          </i-input>
        </FormItem>
        <FormItem label="商家选择" prop="url" v-if="advertType === 'STORE_HOME'">
          <Select v-model="form.url" style="width:100%" filterable>
            <Option  v-for="item in merchantData" :key="item.id" :value="item.id">{{item.shopName}}</Option>
          </Select>
        </FormItem>
        <FormItem label="商品选择" prop="url" v-if="advertType === 'GOOD_PAGE'">
          <Select v-model="form.url" style="width:100%" filterable>
            <Option  v-for="item in goodsData" :key="item.id" :value="item.id">{{item.goodName}}</Option>
          </Select>
        </FormItem>
        <FormItem label="作品选择" prop="url" v-if="advertType === 'GOOD_PACKAGE_PAGE'">
          <Select v-model="form.url" style="width:100%" filterable>
            <Option  v-for="item in mealData" :key="item.id" :value="item.id">{{item.goodName}}</Option>
          </Select>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="modalVisible=false">取消</Button>
        <Button type="primary" :loading="submitLoading" @click="handleSubmit">提交</Button>
      </div>
    </Modal>

    <Modal title="查看大图" v-model="visible" :width="600">
      <img :src="imgUrl" style="width: 100%">
    </Modal>

    <Modal
      v-model="videoVisible"
      title="视频播放"
      :width="600"
      @on-cancel="closeVideo"
      draggable
    >
      <div id="dplayer" style="height: 500px"></div>
    </Modal>
  </div>
</template>

<script>
import "dplayer/dist/DPlayer.min.css";
import DPlayer from "dplayer";
var dp;
import {
  getUserListData, uploadFile
} from "@/api/index";
import circleLoading from "@/views/my-components/circle-loading.vue";
import uploadVideoInput from "@/views/my-components/xboot/upload-video-input.vue"
export default {
  name: "staffManagement",
  components: {
    circleLoading,
    uploadVideoInput
  },
  data() {
    return {
      videoVisible: false,
      loading: true, // 表单加载状态
      loadingEdit: false,
      modalType: 0, // 添加或编辑标识
      modalVisible: false, // 添加或编辑显示
      modalTitle: "", // 添加或编辑标题
      searchForm: { // 搜索框初始化对象
        pageNumber: 1, // 当前页数
        pageSize: 10, // 页面大小
        advertisingType: "",
        advertisingJumpType: ""
      },
      form: { // 添加或编辑表单对象初始化数据
        advertisingType: "",
        advertisingJumpType: "",
        pic: "",
        url: "",
      },
      selectData:[],
      // 表单验证规则
      formValidate: {
        advertisingType: [{ required: true, message: "请选择广告类型", trigger: "change" }],
        advertisingJumpType: [{ required: true, message: "请选择跳转类型", trigger: "change" }],
        pic: [{ required: true, message: "请选择文件", trigger: "change" }],
        url: [{ required: true, message: "请输入链接" }],
      },
      submitLoading: false, // 添加或编辑提交状态
    //   selectList: [], // 多选数据
      selectCount: 0, // 多选计数
      columns: [
        // 表头
        {
          type: "index",
          width: 60,
          align: "center"
        },
        {
          title: "文件",
          key: "pic",
          minWidth: 120,
          sortable: false,
          render: (h, params) => {
            // var imgs = params.row.pic;
            var index= params.row.pic.lastIndexOf(".");
            //获取后缀
            var ext = params.row.pic.substr(index+1);
            //输出结果
            console.log(ext);
            if (ext === 'mp4' || ext === 'avi') {
              return h("video",
                {
                  style: {
                    cursor: "pointer",
                    width: "80px",
                    height: "60px",
                    margin: "10px 0",
                    "object-fit": "contain"
                  },
                  on: {
                    click: () => {
                      this.showVideo(params.row);
                    }
                  }
                },
                [
                  h("source", {
                    attrs: {
                      src: params.row.pic
                    }
                  })
                ]
              );
            } else {
              return h("img", {
                attrs: {
                  src: params.row.pic
                },
                style: {
                  width: "30px",
                  height: "30px"
                },
                on: {
                  click: ()=> {
                    this.handleView(params.row.pic)
                  }
                }
              });
            }
          }
        },
        {
          title: "链接地址",
          key: "url",
          minWidth: 120,
          sortable: false,
        },
        {
          title: "广告类型",
          key: "advertisingType",
          minWidth: 120,
          sortable: false,
        },
        {
          title: "跳转类型",
          key: "advertisingJumpType",
          minWidth: 120,
          sortable: false,
        },
        // {
        //   title: "创建时间",
        //   key: "createTime",
        //   minWidth: 120,
        //   sortable: false,
        // },
        {
          title: "操作",
          key: "action",
          align: "center",
          minWidth: 400,
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small",
                    icon: "ios-create-outline"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.edit(params.row);
                    }
                  }
                },
                "编辑"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small",
                    icon: "md-trash"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.remove(params.row);
                    }
                  }
                },
                "删除"
              ),
            ]);
          }
        }
      ],
      data: [], // 表单数据
      classifyData: [],
      type:"",
      total: 0, // 表单数据总数
      advertType: 0,
      type: "",
      merchantData: [],
      goodsData: [],
      mealData: [],
      fileData: '',
      accessToken: {},
      uploadFileUrl: uploadFile,
      imgUrl: "",
      visible: false
    };
  },
  methods: {
    init() {
      this.getDataList();
      this.getMerchantList();
      this.getGoodsList();
      this.getMealList();
      this.accessToken = {
        accessToken: this.getStore("accessToken")
      };
    },
    download (e) {
      console.log(e.pic);
      window.open(e.pic)
    },
    handleView(url) {
      this.imgUrl = url;
      this.visible = true;
    },
    showVideo(v) {
      dp = new DPlayer({
        container: document.getElementById("dplayer"),
        screenshot: true,
        video: {
          url: v.pic
        },
      });
      this.videoVisible = true;
    },
    closeVideo() {
      dp.destroy();
    },
    handleSuccess(res, file) {
      this.loading = false;
      if (res.success) {
        file.url = res.result;
        this.fileData = res.result;
        console.log(this.fileData)
      } else {
        this.$Message.error(res.message);
      }
    },

    changePage(v) {
      this.searchForm.pageNumber = v;
      this.getDataList();
      this.clearSelectAll();
    },
    changePageSize(v) {
      this.searchForm.pageSize = v;
      this.getDataList();
    },
    handleReset() {
      this.$refs.searchForm.resetFields();
      this.searchForm.pageNumber = 1;
      this.searchForm.pageSize = 10;
      // 重新加载数据
      this.getDataList();
    },
    changeSort(e) {
      this.searchForm.sort = e.key;
      this.searchForm.order = e.order;
      if (e.order === "normal") {
        this.searchForm.order = "";
      }
      this.getDataList();
    },
    clearSelectAll() {
      this.$refs.table.selectAll(false);
      this.searchForm.advertisingType=''
      this.searchForm.advertisingJumpType=''
    },
    selectAdvertType (e) {
      this.form.url = "";
      this.advertType = e;
    },
    changeType (e) {
      console.log(e);
      this.type = e;
    },
    getDataList() {
      this.searchForm.advertisingJumpType == undefined ? this.searchForm.advertisingJumpType = "" : ""
      this.searchForm.advertisingType == undefined ? this.searchForm.advertisingType = "" : ""
        this.loading = true;
        this.postRequest("/advertising/getBackAdvertisingList", this.searchForm).then(res => {
            this.loading = false;
            if (res.success) {
              this.data = res.result.dataResult;
              this.total = res.result.totalPage;
            } else if (res.code == 201) {
              this.data=[];
              this.total=0;
            }
        });
    },
    getMerchantList () {
      this.postRequest("/user/getBackUserStoreList").then(res=> {
        if (res.success) {
          this.merchantData = res.result.data;
        } else {
          this.merchantData = []
        }
      })
    },
    getGoodsList () {
      this.postRequest("/good/PCgoodsList").then(res=> {
        if (res.success) {
          this.goodsData = res.result.data;
        } else {
          this.goodsData = []
        }
      })
    },
    getMealList () {
      this.postRequest("/good/PCgoodsPackageList").then(res=> {
        if (res.success) {
          this.mealData = res.result.data;
        } else {
          this.mealData = []
        }
      })
    },
    getClassifyList() {
        var data = {
            pid: ""
        }
        this.postRequest("/goodCategory/getGoodCategoryList",data).then(res => {
            this.loading = false;
            if (res.success) {
                res.result.forEach(function(e) {
                  e.title=e.title;
                  if (e.isParent) {
                    e.loading = false;
                    e.children = [];
                  }
                });
              this.classifyData = res.result;
            }
        });
    },
    loadData(item, callback) { 
        // 异步加载树子节点数据
      var param ={
        pid:item.id
      }
      this.postRequest("/goodCategory/getGoodCategoryList",param).then(res => {
        if (res.success) {
          res.result.forEach(function(e) {
            e.title=e.title
            if (e.isParent) {
              e.loading = false;
              e.children = [];
            }
          });
          callback(res.result);
        }
      });
    },
    selectTreeEdit(v){
        this.form.classifyId = v[0].id;
        this.form.classifyName = v[0].title;
        this.$forceUpdate();
    },
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.submitLoading = true;
          if (this.advertType === "H5_WEB") {
            this.form.url = "https://"+this.form.url
          }
          if (this.modalType === 0) {
            // 添加 避免编辑后传入id等数据 记得删除
            delete this.form.id;
            this.postRequest("/advertising/insertOrderUpdateAdvertising", this.form).then(res => {
              this.submitLoading = false;
              if (res.success) {
                this.$Message.success("操作成功");
                this.getDataList();
                this.modalVisible = false;
              }
            });
          } else {
            this.postRequest("/advertising/insertOrderUpdateAdvertising", this.form).then(res => {
              this.submitLoading = false;
              if (res.success) {
                this.$Message.success("操作成功");
                this.getDataList();
                this.modalVisible = false;
              }
            });
          }
        }
      });
    },
    add() {
      this.modalType = 0;
      this.modalTitle = "添加";
      this.$refs.form.resetFields();
      this.advertType = "";
      this.type = "";
      this.form.pic = "";
      delete this.form.id;
      this.modalVisible = true;
    },
    edit(v) {
      console.log(v)
      this.modalType = 1;
      this.modalTitle = "编辑";
      this.$refs.form.resetFields();
      // 转换null为""
      for (let attr in v) {
        if (v[attr] === null) {
          v[attr] = "";
        }
      }
      let str = JSON.stringify(v);
      let data = JSON.parse(str);
      this.advertType = data.advertisingJumpType;
      this.type = data.advertisingType;
      this.form = data;
      if (data.advertisingJumpType === "商品详情页") {
        this.advertType = "GOOD_PAGE";
        this.form.advertisingJumpType = "GOOD_PAGE"
      } else if (data.advertisingJumpType === "H5网页链接") {
        this.advertType = "H5_WEB";
        this.form.advertisingJumpType = "H5_WEB"
      } else if (data.advertisingJumpType === "商家店铺首页") {
        this.advertType = "STORE_HOME";
        this.form.advertisingJumpType = "STORE_HOME"
      } else if (data.advertisingJumpType === "套餐详情页") {
        this.advertType = "GOOD_PACKAGE_PAGE";
        this.form.advertisingJumpType = "GOOD_PACKAGE_PAGE"
      }

      if (data.advertisingType === "开屏") {
        // this.advertType = "GOOD_PAGE";
        this.form.advertisingType = "OPEN_HOME"
      } else if (data.advertisingType === "轮播") {
        // this.advertType = "H5_WEB";
        this.form.advertisingType = "BANNER"
      }


      

      // <Form-item label="广告类型" prop="advertisingType">
      //     <Select v-model="form.advertisingType" style="width:100%" @on-change="changeType">
      //       <Option value="OPEN_HOME">开屏</Option>
      //       <Option value="BANNER">轮播</Option>
      //     </Select>
      //   </Form-item>
      //   <Form-item label="广告跳转类型" prop="advertisingJumpType">
      //     <Select v-model="form.advertisingJumpType" style="width:100%" @on-change="selectAdvertType">
      //       <Option value="H5_WEB">外部链接</Option>
      //       <Option value="STORE_HOME">商家首页</Option>
      //       <Option value="GOOD_PAGE">商品详情页</Option>
      //       <Option value="GOOD_PACKAGE_PAGE">作品详情页</Option>
      //     </Select>
      //   </Form-item>
      console.log(this.form)
      delete this.form._index;
      delete this.form._rowKey;
      this.modalVisible = true;
    },
    remove(v){
      this.$Modal.confirm({
        title: "确认删除",
        // 记得确认修改此处
        content: "您确认要删除?",
        loading: true,
        onOk: () => {
          var param={
            ids:v.id
          }
          this.postRequest("/advertising/removeAdvertising",param).then(res => {
            this.$Modal.remove();
            if (res.success) {
              this.$Message.success("操作成功");
              this.getDataList();
            }
          });
        }
      });
    },
    delAll() {
        console.log(this.data)
        if (this.selectCount <= 0) {
            this.$Message.warning("您还未选择要删除的数据");
            return;
        }
        this.$Modal.confirm({
            title: "确认删除",
            content: "您确认要删除所选的数据?",
            loading: true,
            onOk: () => {
            // 批量删除
                this.postRequest("/size/removeSize",{id:this.brandId}).then(res => {
                    this.$Modal.remove();
                    if (res.success) {
                        this.$Message.success("操作成功");
                        this.clearSelectAll();
                        this.getDataList();
                    }
                })
            // 模拟请求成功
                this.$Message.success("操作成功");
                this.$Modal.remove();
                this.clearSelectAll();
                this.getDataList();
            }
        })
    }
},
  mounted() {
    this.init();
  }
};
</script>
<style lang="less">
.search {
    .operation {
        margin-bottom: 2vh;
    }
    .select-count {
        font-size: 13px;
        font-weight: 600;  
        color: #40a9ff;
    }
    .select-clear {
        margin-left: 10px;
    }
    .page {
        margin-top: 2vh;
    }
    .drop-down {
        font-size: 13px;
        margin-left: 5px;
    }
}
</style>